//
//  CollectionDataHandle.m
//  LQH-Douban
//
//  Created by lanou3g on 15/10/26.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "CollectionDataHandle.h"
#import <AVUser.h>
#import <sqlite3.h>
#import "Message.h"
#import "Movie.h"

static CollectionDataHandle *collection = nil;

@interface CollectionDataHandle ()




@end

@implementation CollectionDataHandle

+ (instancetype)sharedCollection
{
    if (collection == nil) {
        
        collection = [[CollectionDataHandle alloc] init];
    }
    
    return collection;
}

// 懒加载

- (NSMutableArray *)activityArray
{
    if (_activityArray == nil) {
        
        self.activityArray = [NSMutableArray array];
        
        [self getActList];
    }
    
    
    return _activityArray;
}

- (NSMutableArray *)movieArray
{
    if (_movieArray == nil) {
        
        self.movieArray = [NSMutableArray array];
        
        [self getMovList];
    }
    
    return _movieArray;
}

- (NSString *)DBPath
{

    if (_DBPath == nil) {
        
        NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        
        NSString *path = [documents stringByAppendingPathComponent:[AVUser currentUser].username];
        
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
        
        self.DBPath = [path stringByAppendingPathComponent:@"collection.sqlite"];
    }
    
    return _DBPath;
}

#pragma mark - 数据库处理

// 数据库指针
static sqlite3 *db;

// 打开数据库
- (void)openDB
{
    int result = sqlite3_open(self.DBPath.UTF8String, &db);
    
    NSLog(@"%@", self.DBPath);
    
    
    if (result != SQLITE_OK) {
        
        NSLog(@"打开数据库失败");
    }
}

// 关闭数据库
- (void)closeDB
{
    int result = sqlite3_close(db);
    
    if (result != SQLITE_OK) {
        
        NSLog(@"关闭数据库失败");
    }
}

#pragma mark - activity
// 创建表
- (void)createTableAct
{
    NSString *sqlStr = @"create table if not exists act (a_id integer primary key not null, a_title text, a_begin_time text, a_end_time text, a_address text, a_category_name text, a_wisher_count integer, a_participant_count integer, a_image blob, a_name text, a_content text)";
    
    int result = sqlite3_exec(db, sqlStr.UTF8String, NULL, NULL, NULL);
    
    if (result != SQLITE_OK) {
        
        NSLog(@"创建表失败");
    }

}

// 是否存在活动
- (BOOL)isExistAct:(NSNumber *)a_id
{
    NSString *sqlStr = @"select a_id from act where a_id = ?";
    
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        sqlite3_bind_int(stmt, 1, [a_id intValue]);
        
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            
            sqlite3_finalize(stmt);
            return YES;
        }
        
    } else {
        
        NSLog(@"selct语句出错");
    }
    
    sqlite3_finalize(stmt);
    
    return NO;
    
    

}

// 增加活动
- (void)insertAct:(Message *)message
{
    NSString *sqlStr = @"insert into act (a_id, a_title, a_begin_time, a_end_time, a_address, a_category_name, a_wisher_count, a_participant_count, a_image, a_name, a_content) values (?,?,?,?,?,?,?,?,?,?,?)";
    
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare_v2(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        sqlite3_bind_int(stmt, 1, [message.a_id intValue]);
        sqlite3_bind_text(stmt, 2, message.title.UTF8String, -1, NULL);
        sqlite3_bind_text(stmt, 3, message.begin_time.UTF8String, -1, NULL);
        sqlite3_bind_text(stmt, 4, message.end_time.UTF8String, -1, NULL);
        sqlite3_bind_text(stmt, 5, message.address.UTF8String, -1, NULL);
        sqlite3_bind_text(stmt, 6, message.category_name.UTF8String, -1, NULL);
        sqlite3_bind_int(stmt, 7, [message.wisher_count intValue]);
        sqlite3_bind_int(stmt, 8, [message.participant_count intValue]);
        
        NSData *imgData = UIImageJPEGRepresentation(message.activityImg, 1.0);
        sqlite3_bind_blob(stmt, 9, [imgData bytes], (int)[imgData length], NULL);
        
        sqlite3_bind_text(stmt, 10, message.name.UTF8String, -1, NULL);
        sqlite3_bind_text(stmt, 11, message.content.UTF8String, -1, NULL);
        
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            
            NSLog(@"插入成功");
            [self.activityArray addObject:message];
            
        } else {
            
            NSLog(@"插入失败");
        }
        
        
        
    } else {
        
        NSLog(@"insert语句有误");
    }
    
    sqlite3_finalize(stmt);
}

- (void)deleteActWithId:(NSNumber *)a_id
{
    NSString *sqlStr = @"delete from act where a_id = ?";
    
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        sqlite3_bind_int(stmt, 1, [a_id intValue]);
        
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            
            NSLog(@"删除成功");
        } else {
            NSLog(@"删除失败");
        }
        
    } else {
        NSLog(@"delte语句出错");
    }
}


- (void)getActList
{
    
    NSString * sqlStr = @"select a_id, a_title, a_begin_time, a_end_time, a_address, a_category_name, a_wisher_count, a_participant_count, a_image, a_name, a_content from act";
    
    
    sqlite3_stmt *stmt = NULL;
    
    int result = sqlite3_prepare_v2(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            Message *m = [[Message alloc] init];
            
            m.a_id = [NSNumber numberWithInt:sqlite3_column_int(stmt, 0)];
            m.title = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
            m.title = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            m.begin_time = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
            m.end_time = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
            m.address = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];
            m.category_name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 5)];
            m.wisher_count = [NSNumber numberWithInt:sqlite3_column_int(stmt, 6)];
            m.participant_count = [NSNumber numberWithInt:sqlite3_column_int(stmt, 7)];
            
#warning 读取图片
            int bytes = sqlite3_column_bytes(stmt, 8);
            Byte *value = (Byte *)sqlite3_column_blob(stmt, 8);
            
            NSData * data = [NSData dataWithBytes:value length:bytes];
            
            UIImage * img = [UIImage imageWithData:data];
            
            m.activityImg = img;
            
            m.name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 9)];
            m.content = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 10)];
              
            [self.activityArray addObject:m];
            
        }
        
    } else {
        
        NSLog(@"select语句出错");
    }
    
    sqlite3_finalize(stmt);
    
}

#pragma mark - movie


- (void)createTableMov
{
    //    NSString *sqlStr = @"create table if not exists mov (a_title text primary key not null)";
    
    NSString *sqlStr = @"create table if not exists mov (m_id integer primary key not null, m_title text, m_rating integer, m_runtime text, m_genres text, m_country text, m_actors text, m_plot_simple text, m_rating_count integer, m_image blob)";
    
    int result = sqlite3_exec(db, sqlStr.UTF8String, NULL, NULL, NULL);
    
    if (result != SQLITE_OK) {
        
        NSLog(@"创建表失败");
    }
}


// 是否存在活动
- (BOOL)isExistMov:(NSString *)title
{
    NSString *sqlStr = @"select m_title from mov where m_title = ?";
    
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        sqlite3_bind_text(stmt, 1, title.UTF8String, -1, NULL);
        
        if (sqlite3_step(stmt) == SQLITE_ROW) {
            
            sqlite3_finalize(stmt);
            return YES;
        }
        
    } else {
        
        NSLog(@"selct语句出错");
    }
    
    sqlite3_finalize(stmt);
    
    return NO;
}

- (void)insertMov:(Movie *)movie
{
//    NSString *sqlStr = @"insert into mov (a_title) values (?)";
    
    NSString *sqlStr = @"insert into mov (m_id, m_title, m_rating, m_runtime, m_genres, m_country, m_actors, m_plot_simple, m_rating_count, m_image) values (?,?,?,?,?,?,?,?,?,?)";
    
    
    sqlite3_stmt *stmt = nil;
    
    int result = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        sqlite3_bind_int(stmt, 1, [movie.movieId intValue]);
        
        sqlite3_bind_text(stmt, 2, movie.title.UTF8String, -1, NULL);

        sqlite3_bind_double(stmt, 3, [movie.rating doubleValue]);
        
        sqlite3_bind_text(stmt, 4, movie.runtime.UTF8String, -1, NULL);
        
        sqlite3_bind_text(stmt, 5, movie.genres.UTF8String, -1, NULL);
        
        sqlite3_bind_text(stmt, 6, movie.country.UTF8String, -1, NULL);
        
        sqlite3_bind_text(stmt, 7, movie.actors.UTF8String, -1, NULL);
        
        sqlite3_bind_text(stmt, 8, movie.plot_simple.UTF8String, -1, NULL);
        
        sqlite3_bind_int(stmt, 9, [movie.rating_count intValue]);
        
//         转化为二进制
        NSData *imgData = UIImageJPEGRepresentation(movie.myImage, 1.0);
        sqlite3_bind_blob(stmt, 10, [imgData bytes], (int)[imgData length], NULL);

        
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            
            NSLog(@"插入成功");
            [self.movieArray addObject:movie];
            
            
        } else {
            
            NSLog(@"插入失败");
        }
        
        
        
    } else {
        
        NSLog(@"insert语句有误");
    }
    
    sqlite3_finalize(stmt);

    
}

- (void)getMovList
{
    NSString * sqlStr = @"select m_id, m_title, m_rating, m_runtime, m_genres, m_country, m_actors, m_plot_simple, m_rating_count, m_image from mov";
    
//    NSString *sqlStr = @"select * from mov";
    
    
    sqlite3_stmt *stmt = NULL;
    
    int result = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (result == SQLITE_OK) {
        
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            Movie *m = [[Movie alloc] init];
            
            m.movieId = [NSNumber numberWithInt:sqlite3_column_int(stmt, 0)];
            m.title = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
            m.rating = [NSNumber numberWithDouble:sqlite3_column_double(stmt, 2)];
            m.runtime = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
            m.genres = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];
            m.country = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 5)];
            m.actors = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 6)];
            m.plot_simple = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 7)];
            m.rating_count = [NSNumber numberWithInt:sqlite3_column_int(stmt, 8)];
            
            int bytes = sqlite3_column_bytes(stmt, 9);
            Byte *value = (Byte *)sqlite3_column_blob(stmt, 9);
            NSData * data = [NSData dataWithBytes:value length:bytes];
            UIImage * img = [UIImage imageWithData:data];
            m.myImage = img;
            
            [self.movieArray addObject:m];
            
        }
        
    } else {
        
        NSLog(@"select语句出错");
    }
    
    sqlite3_finalize(stmt);
}

// 清除缓存
- (void)clearAct
{
    NSString *sqlStr = @"delete from act";
    
    sqlite3_stmt *stmt;
    
    int reslut = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (reslut == SQLITE_OK) {
        
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            
            NSLog(@"删除成功");
            [self.activityArray removeAllObjects];
            
        } else {
            NSLog(@"删除失败");
        }
        
    } else {
        NSLog(@"delete 语句错误");
    }
    
    sqlite3_finalize(stmt);

    
    
}

- (void)clearMov
{
    NSString *sqlStr = @"delete from mov";
    
    sqlite3_stmt *stmt;
    
    int reslut = sqlite3_prepare(db, sqlStr.UTF8String, -1, &stmt, NULL);
    
    if (reslut == SQLITE_OK) {
        
        if (sqlite3_step(stmt) == SQLITE_DONE) {
            
            NSLog(@"删除成功");
            [self.movieArray removeAllObjects];
            
        } else {
            NSLog(@"删除失败");
        }
        
    } else {
        NSLog(@"delete 语句错误");
    }
    
    sqlite3_finalize(stmt);
    
    
}

@end
